const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const koaJwt = require('koa-jwt')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')
const auth = require('./middleware/auth')
const login = require('./routes/login')
const api = require('./routes/api')
const config = require('./config/index')
const { secret } = config

onerror(app)

// 中间件
// 跨域访问中间件
app.use(cors({
    origin: '*',
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST',],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
// 授权认证中间件
app.use(auth())
app.use(koaJwt({
    secret
}).unless({
    path: [/\/login/]
}))

app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))

// 路由
app.use(login.routes(), login.allowedMethods())
app.use(api.routes(), api.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app
